package com.blog.admin.service.impl;

import com.blog.admin.mapper.AdminMapper;
import com.blog.admin.pojo.Admin;
import com.blog.admin.service.AdminService;
import com.blog.admin.util.AdminUtil;
import com.blog.common.utils.Assert;
import com.blog.common.utils.StringsUtils;
import com.blog.common.utils.UUIDUtils;
import com.blog.common.vo.JsonResult;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public JsonResult login(Admin admin) {
        JsonResult res;
        String pwd = admin.getPassword();
        admin = adminMapper.findByAccount(admin);
        Assert.valid(admin, "该账号不存在");
        String salt = admin.getSalt();
        pwd = AdminUtil.getMD5Str(pwd + salt);
        if (!admin.getPassword().equals(pwd)) {
            res = JsonResult.fail("账号或密码错误");
        } else {
            Map<String, String> data = new HashMap<>();
            data.put("token", salt);
            res = JsonResult.success(data);
        }
        return res;
    }

    @Override
    public JsonResult saveOrUpdateAdmin(Admin admin) {
        Assert.valid(admin, "管理员信息不能为空！");
        String salt = UUIDUtils.getUUID();
        String base = admin.getPassword() + salt;
        String password = AdminUtil.getMD5Str(base);
        admin.setPassword(password);
        admin.setSalt(salt);
        admin.setUpdateTime(new Date());
        if(StringsUtils.isBlank(admin.getId())){ //保存
            admin.setNewId();
            admin.setCreateTime(new Date());
            int rs = adminMapper.insertAdmin(admin);
            Assert.decide(rs, "注册失败，请稍后再试！");
        } else{ //更新
            int rs = adminMapper.updateAdmin(admin);
            Assert.decide(rs, "修改失败，请稍后再试！");
        }

        return JsonResult.success();
    }

    @Override
    public JsonResult getInfo(String token) {
        Admin admin = adminMapper.findBySalt(token);
        Assert.valid(admin, "token不正确或失效");
        return JsonResult.success(admin);
    }

}
